package jehc.djshi.oauth.web;

import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jehc.djshi.common.annotation.AuthUneedLogin;
import jehc.djshi.common.base.BaseAction;
import jehc.djshi.common.base.BaseResult;
import jehc.djshi.common.base.BaseToken;
import jehc.djshi.common.constant.CacheConstant;
import jehc.djshi.common.constant.SessionConstant;
import jehc.djshi.common.constant.StatusConstant;
import jehc.djshi.common.session.HttpSessionUtils;
import jehc.djshi.common.util.JsonUtil;
import jehc.djshi.common.util.StringUtil;
import jehc.djshi.oauth.constant.Constant;
import jehc.djshi.oauth.model.OauthKeyInfo;
import jehc.djshi.oauth.util.OauthUtil;
import jehc.djshi.oauth.vo.Transfer;
import jehc.djshi.oauth.vo.TransferSub;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
 * @Desc 授权中心Sync同步功能API
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@RestController
@Api(value = "授权中心Sync同步功能API",tags = "授权中心Sync同步功能API",description = "授权中心Sync同步功能API")
@Slf4j
public class SyncController extends BaseAction {

    @Autowired
    HttpSessionUtils httpSessionUtils;

    @Autowired
    private OauthUtil oauthUtil;

    /**
     * 验证SysMode是否合法
     * @param request
     * @return
     */
    @AuthUneedLogin
    @GetMapping(value="/validateSys")
    @ApiOperation(value="验证SysMode是否合法", notes="验证SysMode是否合法")
    private BaseResult validateSys(HttpServletRequest request){
        String key = null;
        String pass = null;
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String k = (String) headerNames.nextElement();
            if(k.toLowerCase().equals(CacheConstant.JEHC_CLOUD_KEY.toLowerCase())){
                key = request.getHeader(k);
            }
            if(k.toLowerCase().equals(CacheConstant.JEHC_CLOUD_SECURITY.toLowerCase())){
                pass = request.getHeader(k);
            }
        }
        if(StringUtil.isEmpty(key)){
            return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_999,"未能获取到平台Key",false);
        }
        if(StringUtil.isEmpty(pass)){
            return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_999,"未能获取到平台秘钥",false);
        }
        String oauthKeyInfoJson = httpSessionUtils.getHashAttribute(CacheConstant.OAUTH_KEY,key);
        OauthKeyInfo oauthKeyInfo = JsonUtil.fromFJson(oauthKeyInfoJson,OauthKeyInfo.class);
        if(null == oauthKeyInfo || StringUtil.isEmpty(oauthKeyInfo.getKey_pass())){
            return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_999,"平台秘钥不存在",false);
        }
        String key_pass = oauthKeyInfo.getKey_pass();
        if(!pass.equals(key_pass)){
            return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_999,"平台秘钥不正确",false);
        }
        return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_200,"平台秘钥合法",true,key);
    }

    /**
     * signature
     * @param map
     * @return
     */
    @AuthUneedLogin
    @PostMapping(value="/signature")
    @ApiOperation(value="signature", notes="signature")
    private BaseResult signature(@RequestBody Map<String,String> map){
        String key = null;
        String pass = null;
        if(!CollectionUtil.isEmpty(map)){
            key = map.get("jehcCloudKey");
            pass = map.get("jehcCloudSecurity");
        }
        if(StringUtil.isEmpty(key)){
            return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_999,"未能获取到平台Key",false);
        }
        if(StringUtil.isEmpty(pass)){
            return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_999,"未能获取到平台秘钥",false);
        }
        String oauthKeyInfoJson = httpSessionUtils.getHashAttribute(CacheConstant.OAUTH_KEY,key);
        OauthKeyInfo oauthKeyInfo = JsonUtil.fromFJson(oauthKeyInfoJson,OauthKeyInfo.class);
        if(null == oauthKeyInfo || StringUtil.isEmpty(oauthKeyInfo.getKey_pass())){
            return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_999,"平台秘钥不存在",false);
        }
        String key_pass = oauthKeyInfo.getKey_pass();
        if(!pass.equals(key_pass)){
            return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_999,"平台秘钥不正确",false);
        }
        return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_200,"平台秘钥合法",true,key);
    }

    /**
     * 更新Token有效期
     * @param map
     * @return
     */
    @AuthUneedLogin
    @PostMapping(value="/updateExpire")
    @ApiOperation(value="更新Token有效期", notes="更新Token有效期")
    private BaseResult updateExpire(@RequestBody Map<String,String> map){
        String token = null;
        BaseToken baseToken = null;
        if(!CollectionUtil.isEmpty(map)){
            token = map.get("token");
            baseToken = JsonUtil.fromAliFastJson(map.get("tokenInfo"),BaseToken.class);
        }
        if(StringUtil.isEmpty(token)){
            return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_999,"未能获取到Token",false);
        }
        if(null == baseToken){
            return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_999,"未能获取到Token更新信息",false);
        }

        if(httpSessionUtils.setAttributeExpTime(SessionConstant.TOKEN_STORE_PATH+token,12)){
            httpSessionUtils.setAttributeExpTime(SessionConstant.ACCOUNT_STORE_PATH+baseToken.getClientId(),12);//单独存放Account编号维护Token
        }
        return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_200,"Token有效期更新成功",true);
    }

    /**
     * 批量更新Token有效期
     * @param map
     * @return
     */
    @AuthUneedLogin
    @PostMapping(value="/batchUpdateExpire")
    @ApiOperation(value="更新Token有效期", notes="更新Token有效期")
    private BaseResult batchUpdateExpire(@RequestBody Map<String,BaseToken> map){
        Map<String,BaseToken> resMap = new HashMap<>();
        if(!CollectionUtil.isEmpty(map)){
            Iterator<Map.Entry<String, BaseToken>> entries = map.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, BaseToken> entry = entries.next();
                BaseToken baseToken = entry.getValue();
                baseToken.setUpdateTimes(getSimpleDateFormat());
                if(StringUtil.isEmpty(entry.getKey())){
                    log.warn("未能获取到Token，更新信息失败,{}",entry);
                    continue;
                }
                if(null == baseToken){
                    log.warn("未能获取到Token client，更新信息失败,{}",entry);
                    continue;
                }
                if(httpSessionUtils.setAttributeExpTime(SessionConstant.TOKEN_STORE_PATH+entry.getKey(),12)){
                    httpSessionUtils.setAttributeExpTime(SessionConstant.ACCOUNT_STORE_PATH+baseToken.getClientId(),12);//单独存放Account编号维护Token
                }
                resMap.put(entry.getKey(),entry.getValue());
            }
        }
        return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_200,"Token有效期更新成功",true,resMap);
    }


    /**
     * 批量操作Token
     * @param map
     * @return
     */
    @AuthUneedLogin
    @PostMapping(value="/batchToken")
    @ApiOperation(value="批量操作Token", notes="批量操作Token")
    private BaseResult batchToken(@RequestBody Map<String,Transfer> map){
        Map<String,TransferSub> resMap = new HashMap<>();
        if(!CollectionUtil.isEmpty(map)){
            Iterator<Map.Entry<String, Transfer>> entries = map.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, Transfer> entry = entries.next();
                Transfer transfer = entry.getValue();
                if(StringUtil.isEmpty(entry.getKey())){
                    log.warn("未能获取到Token info,{}",entry);
                    resMap.put(entry.getKey(),new TransferSub(transfer.getToken(),false,null));
                    continue;
                }
                if(null == transfer){
                    log.warn("未能获取到Token info,{}",entry);
                    resMap.put(entry.getKey(),new TransferSub(transfer.getToken(),false,null));
                    continue;
                }
                if(transfer.getActionType().equals(Constant.OAUTH_CHANGED)){//如果客户端拉取Token信息
                    String info = oauthUtil.getTokenInfo(entry.getKey());
                    resMap.put(entry.getKey(),new TransferSub(transfer.getToken(),true,info));
                }
            }
        }
        return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_200,"批量操作Token成功",true,resMap);
    }

    /**
     * 验证Token是否过期
     * @param map
     * @return
     */
    @AuthUneedLogin
    @PostMapping(value="/batchTokenValid")
    @ApiOperation(value="验证Token是否过期", notes="验证Token是否过期")
    private BaseResult batchTokenValid(@RequestBody Map<String,Integer> map){
        Map<String,Integer> resMap = new HashMap<>();
        if(!CollectionUtil.isEmpty(map)){
            Iterator<Map.Entry<String, Integer>> entries = map.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, Integer> entry = entries.next();
                if(StringUtil.isEmpty(entry.getKey())){
                    log.warn("未能获取到Token对象,{}",entry);
                    resMap.put(entry.getKey(),-1);
                    continue;
                }
                if(StringUtil.isEmpty(oauthUtil.getTokenInfo(entry.getKey()))){//如果客户端拉取Token信息
                    resMap.put(entry.getKey(),-1);
                }else{
                    resMap.put(entry.getKey(),1);
                }
            }
        }
        return new BaseResult(StatusConstant.XT_PT_STATUS_VAL_200,"批量操作Token成功",true,resMap);
    }
}
